package com.zyg.config;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.core.Authentication;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    /*
    AuthenticationEntryPoint 接口的作用是当用户未通过身份验证（例如，JWT 验证失败时），
    Spring Security 会调用该接口的 commence() 方法，这样就可以进行自定义的异常处理或跳转处理。

    //抛出异常时被这个配置类捕获
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 这里可以设置返回的错误信息
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "token过期或者失效");
    }
}
